<template>
  <div class="knowledge-edit-page">
    <CrumbContent name="创建知识库" @back="emit('back')" />

    <Steps :current="stepCurrent">
      <Step v-for="(title,index) in STEP_OPTIONS" :key="index" :title="title" />
    </Steps>

    <div class="body-content">
      <p v-for="(item,index) in STEP_OPTIONS" :key="index" v-show="stepCurrent === index"
        class="step-title">{{item}}</p>

      <!-- <p v-if="stepCurrent === 1" class="step-desc">
        从数据中心选择导入的数据,并构建知识库索引.新增文档请前往
        <a href="">数据中心
          <Icon type="md-arrow-round-up" size="20" /></a>
      </p> -->

      <Form ref="formEl" :model="formData" :rules="rules" :label-width="100">
        <template v-if="!stepCurrent">
          <FormItem label="知识库名称" prop="name">
            <Input v-model="formData.name" maxlength="20" show-word-limit placeholder="请输入知识库名称" />
          </FormItem>

          <FormItem label="知识库描述">
            <Input v-model="formData.description" type="textarea" maxlength="1000" show-word-limit
              :rows="5" placeholder="请输入知识库描述" />
          </FormItem>

          <FormItem label="数据类型">
            <CardList v-model="formData.kbdoctype" :data="DATA_TYPE_OPTIONS" />
          </FormItem>
        </template>

        <template v-if="stepCurrent === 1">
          <template v-if="formData.kbdoctype === 'table'">
            <FormItem label="数据来源" :label-width="88">
              <CardList v-model="formData.cardId1" :data="DATA_FROM_OPTIONS" />
            </FormItem>

            <FormItem :label-width="88">
              <DataSourceTable @selected="dataSourceSelectData = $event" />
            </FormItem>
          </template>

          <template v-if="formData.kbdoctype === 'doc'">
            <FormItem :label-width="88" prop="files">
              <UploadFile v-model="formData.files" />
            </FormItem>

            <!-- <FormItem label="文档识别" :label-width="88">
              <CardList v-model="formData.cardId2" :data="WORD_OPTIONS" />
            </FormItem> -->

            <FormItem label="配置标签" :label-width="88">
              <p>新增标签(请输入标签，最多32个字符，可通过回车添加)</p>
              <Input v-model="formData.kbtag" type="textarea" maxlength="32" show-word-limit
                :rows="4" placeholder="请输入标签，可通过回车添加。每个标签最多32个字符,支持中文,大小写英文字母,数字,下划线_,中划线-,首尾空格会自动阶段" @on-enter="disposeTags" />

              <div>
                <Tag v-for="(item,index) in tagList" :key="index" type="border" closable
                  @on-close="tagList.splice(index, 1)">{{ item }}
                </Tag>
              </div>
              <p>已使用的标签 (点击可添加)</p>
            </FormItem>
          </template>

        </template>

        <template v-if="stepCurrent === 2">
          <p class="step-title">文件解析设置</p>

          <FormItem label="PDF增强解析" :label-width="94">
            <!-- <CardList v-model="formData.cardId1" :data="ANALYSIS_OPTIONS" height="52px" /> -->
            <Switch v-model="formData.analysisplus" />
          </FormItem>

          <p class="step-title">数据处理方式设置</p>

          <FormItem label="处理方式" :label-width="88">
            <CardList v-model="formData.docparsetype" :data="DISPOSE_OPTIONS" height="52px" />
          </FormItem>

          <FormItem v-if="formData.docparsetype === 'direct'" label="索引增强" :label-width="88">
            <Switch v-model="formData.indexplus" />
          </FormItem>

          <FormItem label="参数设置" :label-width="88">
            <CardList v-model="formData.parseparam" :data="PARAMETER_OPTIONS" height="92px" />
          </FormItem>

          <template v-if="formData.parseparam === 'custom'">
            <FormItem :label-width="88">
              <RadioGroup v-model="formData.parsesplittype" @on-change="parsesplittypeChange">
                <Radio v-for="item in SPLIE_TYPE_OPTIONS" :key="item.value" :label="item.value">{{item.label}}</Radio>
              </RadioGroup>
            </FormItem>

            <FormItem label="重叠字数" :label-width="88">
              <InputNumber v-if="formData.parsesplittype === 'size'"
                v-model="formData.parsechartlength" :min="1" />
              <Select v-else v-model="formData.delimiteroption" transfer>
                <Option v-for="(item,index) in SPLIT_TYPE_OPTIONS" :value="item.value" :key="index">
                  {{item.label}}
                </Option>
              </Select>
            </FormItem>

            <FormItem v-if="formData.parsesplittype !== 'size' && formData.delimiteroption === 'knowCustomize'" label="自定义字符" :label-width="88">
              <Input v-model="formData.parsechartlength" />
            </FormItem>

            <FormItem label="索引大小" :label-width="88">
              <InputNumber v-model="formData.parseindexlength" :min="1" />
            </FormItem>
          </template>
        </template>
      </Form>
    </div>

    <div class="footer-content">
      <Space>
        <Button v-if="stepCurrent" type="primary" @click="lastStep">上一步</Button>
        <Button type="primary" @click="nextStep">{{ stepCurrent === 2 ? '立即提交' : '下一步' }}</Button>
        <Button @click="emit('back')">取消</Button>
      </Space>
    </div>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { Message } from 'view-ui-plus'
import { SPLIT_TYPE_OPTIONS, DISPOSE_OPTIONS, SPLIE_TYPE_OPTIONS, PARAMETER_OPTIONS } from '@/util/conf'
import { myKnowledge } from '@/api/modules/knowledgeBase'
import CardList from './components/CardList.vue'
import UploadFile from './components/UploadFile.vue'
import CrumbContent from '../components/CrumbContent.vue'
import DataSourceTable from './components/DataSourceTable.vue'

const STEP_OPTIONS = ['知识库信息', '选择数据', '数据处理']

const DATA_TYPE_OPTIONS = [
  {
    label: '非结构化数据',
    description: '选择数据管理功能中已传的doc、pdf、md、txt等文件',
    iconConfig: {},
    value: 'doc'
  },
  { label: '结构化数据', description: '选择数据管理功能中已创建的数据表', iconConfig: {}, value: 'table' }
]

const DATA_FROM_OPTIONS = [
  { label: '数据管理', description: '从数据中心选择数据,新增文档请前往数据中心', iconConfig: {}, value: 1 }
  // { label: '关联RDS', description: '直接关联阿里云RDS数据库表,并自动同步数据变更', iconConfig: {}, value: 2 }
]

const WORD_OPTIONS = [
  {
    label: '文档智能解析',
    description: '使用阿里云文档智能解析服务提取和文档，抽取文档内容、原段结构等信息',
    iconConfig: {},
    value: 1
  }
]

const ANALYSIS_OPTIONS = [
  {
    label: 'PDF增强解析',
    value: 1
  }
]

const emit = defineEmits(['back', 'update'])

const typeId = inject('typeId')

const formEl = ref(null)
const stepCurrent = ref(0)
const dataSourceSelectData = ref(null)

const loading = ref(false)
const formData = ref({
  name: '',
  description: '',
  kbdoctype: DATA_TYPE_OPTIONS[0].value,
  kbtag: '',
  analysisplus: false,
  docparsetype: DISPOSE_OPTIONS[0].value,
  indexplus: false,
  parseparam: PARAMETER_OPTIONS[0].value,
  delimiteroption: SPLIT_TYPE_OPTIONS[0].value,

  cardId1: 1,
  parsesplittype: SPLIE_TYPE_OPTIONS[0].value,
  parsechartlength: 1,
  parseindexlength: 1,
  files: []
})

const rules = ref({
  name: [
    { required: true, message: '请填写知识库描述', trigger: 'blur' },
    { required: true, message: '知识库名称已存在', trigger: 'blur', validator: async (row, val, callback) => {
      const data = await myKnowledge.check({
        data: {
          name: val
        }
      })

      if(data.status === 'OK') {
        return callback()
      }
      callback(new Error())
    } }
  ]
  // files: [{ required: true, type: 'array', message: '请上传文件', trigger: 'blur' }]
})

const tagList = ref([])
const disposeTags = () => {
  if (!formData.value.kbtag) return

  const text = formData.value.kbtag.trim()
  try {
    const tags = text.split(',').filter(item => item)
    tagList.value.push(...tags)
    formData.value.kbtag = ''
  } catch (error) {
    Message.error('请使用,隔开')
  }
}

const parsesplittypeChange = () => {
  // const { parsesplittype } = formData.value

  // if (parsesplittype === 'size') {
  //   formData.value.parsechartlength = 1
  // } else {
  //   formData.value.parsechartlength = SPLIT_TYPE_OPTIONS[0].value
  // }
}

const nextStep = async () => {
  if (stepCurrent.value === 2) {
    return submit()
  }

  if (!(await formEl.value.validate())) return

  stepCurrent.value++
}

const lastStep = () => {
  if (stepCurrent.value === 0) {
    return
  }
  stepCurrent.value--
}

const filesUpload = (files, params) => {
  files.forEach(item => {
    myKnowledge.cateUpload({
      upload: item,
      ...params
    })
  })
}

const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    const { files, cardId, cardId1, ...params } = formData.value

    if(params.kbdoctype === 'table' && dataSourceSelectData.value) {
      Object.assign(params, {
        metaid: dataSourceSelectData.value.dbid,
        databasetask: dataSourceSelectData.value.id
      })
    }

    const kbtag = tagList.value.toString()

    const {
      data: { id }
    } = await myKnowledge.cateAdd({
      data: {
        ...params,
        kbtag,
        kbtype: typeId.value
      }
    })

    Message.success('操作成功')

    filesUpload(files, {id, kbtag})

    emit('back')
    emit('update')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}
</script>

<style scoepd lang="scss">
.knowledge-edit-page {
  background-color: #fff;
  height: 100%;
  padding: 20px;
  .ivu-steps {
    padding: 0 20px;
    margin-top: 20px;
  }

  .body-content {
    height: calc(100vh - 260px);
    overflow-y: auto;
    margin-top: 20px;
    .step-title {
      font-weight: bold;
      font-size: 16px;
      margin: 32px 0 16px;
    }
    .step-desc {
      color: #666;
      margin-bottom: 16px;
      .ivu-icon-md-arrow-round-up {
        transform: rotate(45deg);
      }
    }
    .ivu-input-wrapper,
    .ivu-select,
    .el-select,
    .ivu-input-number {
      width: 500px;
    }
  }
  .footer-content {
  }
}
</style>